using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Web.Services.Protocols;

namespace SpiralOut
{
    public partial class ShowHideFields : Form
    {
        DEVListWS.Lists lst;
        private DataSet DsLists = null;
        private DataSet DsFields = null;
        string listName = string.Empty;
        XmlNode ndList;
        string listVersion = string.Empty;
       
        
        public ShowHideFields()
        {
            InitializeComponent();
            linkLabel1.Links[0].LinkData = "http://spyralout.com";
            
        }

        private void label1_Click(object sender, EventArgs e)
        {
            
        }
        public static string CleanUrl(string url)
        {
            string text1 = url;
            if (text1[text1.Length - 1] == '/')
            {
                text1 = text1.Substring(0, text1.Length - 1);
            }
            return text1;
        }
        public static XmlNodeList RunXPathQuery(XmlNode XmlNodeToQuery, string XPathQuery)
        {
            XmlDocument document1 = new XmlDocument();
            document1.LoadXml(XmlNodeToQuery.OuterXml);
            XmlNamespaceManager manager1 = new XmlNamespaceManager(document1.NameTable);
            manager1.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
            manager1.AddNamespace("z", "#RowsetSchema");
            manager1.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois/");
            manager1.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
            manager1.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory/");
            return document1.SelectNodes(XPathQuery, manager1);
        }
        public static string FormatToAllXML(XmlNode oNode)
        {
            StringBuilder ret = new StringBuilder();
            ret.Append(@"<ViewFields xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">");

            foreach (XmlNode oFieldNode in oNode.ChildNodes)
                if (!((!string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["ReadOnly"]))) && (Convert.ToString(oFieldNode.Attributes["ReadOnly"]).ToLower() != "false")))
                {

                    ret.AppendFormat(@"<FieldRef Name=""{0}"" StaticName=""{1}"" DisplayName=""{2}"" Type=""{3}"" ShowInNewForm=""{4}"" ShowInEditForm=""{5}"" ShowInDisplayForm=""{6}"" ShowInViewForms=""{7}""  	 ShowInVersionHistory=""{8}""  Hidden=""{9}""  />"
                        , oFieldNode.Attributes["Name"].Value
                        , oFieldNode.Attributes["StaticName"].Value
                        , oFieldNode.Attributes["DisplayName"].Value
                        , oFieldNode.Attributes["Type"].Value
                        , (string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["ShowInNewForm"])) ? "TRUE" : oFieldNode.Attributes["ShowInNewForm"].Value)
                        , (string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["ShowInEditForm"])) ? "TRUE" : oFieldNode.Attributes["ShowInEditForm"].Value)
                        , (string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["ShowInDisplayForm"])) ? "TRUE" : oFieldNode.Attributes["ShowInDisplayForm"].Value)
                         , (string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["ShowInViewForms"])) ? "TRUE" : oFieldNode.Attributes["ShowInViewForms"].Value)
                         , (string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["ShowInVersionHistory"])) ? "TRUE" : oFieldNode.Attributes["ShowInVersionHistory"].Value)
                         , (string.IsNullOrEmpty(Convert.ToString(oFieldNode.Attributes["Hidden"]))) ? "FALSE" : oFieldNode.Attributes["Hidden"].Value
                        );
                }
            ret.Append("</ViewFields>");

            return ret.ToString();


        }
        public static string GetInnerXMLFromName(XmlNode oNode, string sName)
        {
            XmlDocument document1 = new XmlDocument();
            document1.LoadXml(oNode.OuterXml);
            XmlNamespaceManager manager1 = new XmlNamespaceManager(document1.NameTable);
            manager1.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
            XmlNode node;
            node = oNode.SelectSingleNode(string.Format("sp:Field[@Name='{0}']", sName), manager1);

            return node.InnerXml.Replace(@"xmlns=""http://schemas.microsoft.com/sharepoint/soap/""", "");

        }
        public static string GetOtherAttributesFromName(XmlNode oNode, string sName)
        {
            string sOtherAtttribs = string.Empty;
            XmlDocument document1 = new XmlDocument();
            document1.LoadXml(oNode.OuterXml);
            XmlNamespaceManager manager1 = new XmlNamespaceManager(document1.NameTable);
            manager1.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
            XmlNode node;
            node = oNode.SelectSingleNode(string.Format("sp:Field[@Name='{0}']", sName), manager1);
            XmlAttributeCollection attrCol = node.Attributes;
            XmlAttribute[] arr= new XmlAttribute[attrCol.Count];
            attrCol.CopyTo(arr,0);           
           for (int i = 0; i < attrCol.Count; i++)
           {
               switch (attrCol[i].Name)
               {
                   case "ID":
                       break;
                   case "SourceID":
                       break;
                   case "StaticName":
                       break;
                   case "Version":
                       break;
                   case "RowOrdinal":
                       break;
                   case "Type":
                       break;
                   case "Name":
                       break;
                   case "DisplayName":
                       break;
                   case "ShowInNewForm":
                       break;
                   case "ShowInEditForm":
                       break;
                   case "ShowInDisplayForm":
                       break;
                   case "ShowInViewForms":
                       break;
                   case "ShowInVersionHistory":
                       break;
                   case "Hidden":
                       break;
                   default:
                       sOtherAtttribs += string.Format("{0}='{1}' ", attrCol[i].Name, attrCol[i].Value);
                       break;
               }
           }
           return sOtherAtttribs.ToString();           

        }
        private void btnUpd_Click(object sender, EventArgs e)
        {
            try
            {

                if (!string.IsNullOrEmpty(listName) && !string.IsNullOrEmpty(listVersion))
                {

                    //dataGridView1.DataMember = "Fields";
                    XmlDocument xmlDoc = new System.Xml.XmlDocument();
                    XmlNode ndDeleteFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");
                    XmlNode ndProperties = xmlDoc.CreateNode(XmlNodeType.Element, "List", "");
                    XmlAttribute ndTitleAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "Title", "");
                    XmlAttribute ndDescriptionAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "Description", "");
                    XmlAttribute ndShowUsers = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "ShowUser","");
                    ndShowUsers.Value = Convert.ToString(!cbShowUsr.Checked);
                    XmlNode ndNewFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");
                    ndProperties.Attributes.Append(ndShowUsers);

                    XmlNode ndUpdateFields = null;

                    DataTable dt = ((DataTable)dgvFields.DataSource).GetChanges();
                    int i = 0;
                    if (dt != null)
                    {
                        ndUpdateFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");
                        foreach (DataRow dr in dt.Rows)
                        {

                            if (dr.RowState == DataRowState.Modified)
                            {
                                ndUpdateFields.InnerXml += string.Format("<Method ID='{0}'><Field Type= '{1}' Name='{2}' DisplayName='{3}' ShowInNewForm='{4}' ShowInEditForm='{5}' ShowInDisplayForm='{6}' ShowInViewForms='{7}' 	 ShowInVersionHistory='{8}' Hidden='{9}' {10}>{11}</Field></Method>"
                                       , ++i
                                       , dr["Type"]
                                       , dr["Name"]
                                       , dr["DisplayName"]
                                       , (string.IsNullOrEmpty(dr["ShowInNewForm"].ToString()) ? "FALSE" : Convert.ToString(dr["ShowInNewForm"].ToString()))
                                    , (string.IsNullOrEmpty(dr["ShowInEditForm"].ToString()) ? "FALSE" : Convert.ToString(dr["ShowInEditForm"].ToString()))
                                    , (string.IsNullOrEmpty(dr["ShowInDisplayForm"].ToString()) ? "FALSE" : Convert.ToString(dr["ShowInDisplayForm"].ToString()))
                                     , (string.IsNullOrEmpty(dr["ShowInViewForms"].ToString()) ? "FALSE" : Convert.ToString(dr["ShowInViewForms"].ToString()))
                                    , (string.IsNullOrEmpty(dr["ShowInVersionHistory"].ToString()) ? "FALSE" : Convert.ToString(dr["ShowInVersionHistory"].ToString()))
                                    , (string.IsNullOrEmpty(dr["Hidden"].ToString()) ? "FALSE" : Convert.ToString(dr["Hidden"].ToString()))
                                  , GetOtherAttributesFromName(RunXPathQuery(ndList, "/sp:List/sp:Fields")[0], Convert.ToString(dr["Name"]))
                                  , GetInnerXMLFromName(RunXPathQuery(ndList, "/sp:List/sp:Fields")[0], Convert.ToString(dr["Name"])));
                            }
                            // string test = GetOtherAttributesFromName(RunXPathQuery(ndList, "/sp:List/sp:Fields")[0], Convert.ToString(dr["Name"]));
                        }
                    }
                    try
                    {
                        XmlNode ndReturn =
                        lst.UpdateList(listName,
                                        ndProperties, null, ndUpdateFields, null,
                                        listVersion);
                        MessageBox.Show(ndReturn.OuterXml);
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace);
            }

        }

       

        private void btnLoad_Click(object sender, EventArgs e)
        {
            try
            {
                if (!(string.IsNullOrEmpty(txtUrl.Text)))
                {
                    lst = new DEVListWS.Lists();
                    lst.Url = string.Format("{0}/_vti_bin/Lists.asmx", CleanUrl(this.txtUrl.Text));
                    if (rdCustom.Checked)
                    {
                        this.lst.Credentials = new System.Net.NetworkCredential(txtlogin.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
                    }
                    else
                        lst.Credentials = System.Net.CredentialCache.DefaultCredentials;

                    XmlNode node1 = lst.GetListCollection();
                    this.DsLists = new DataSet();
                    XmlReader reader1 = new XmlNodeReader(node1);
                    this.DsLists.ReadXml(reader1);
                    DataTable dt = this.DsLists.Tables["List"];
                    dt.AcceptChanges();

                    DataColumn dcTitleRender = new DataColumn("TitleRender", System.Type.GetType("System.String"));
                    dcTitleRender.Expression = "IIF(Hidden='False', Title, Title + ' (Hidden)') ";
                    dt.Columns.Add(dcTitleRender);
                    DataView view1 = new DataView(dt);
                    view1.Sort = "Hidden asc, Title asc";
                    this.lstList.DisplayMember = "TitleRender";
                    this.lstList.DataSource = view1;
                    view1 = null;
                    this.DsLists = null;
                }
                else
                    MessageBox.Show("Enter URL");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace);
            }
        }

        private void lstList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (!(string.IsNullOrEmpty(txtUrl.Text)))
                {
                    lst = new DEVListWS.Lists();
                    lst.Url = string.Format("{0}/_vti_bin/Lists.asmx", CleanUrl(this.txtUrl.Text));
                    if (rdCustom.Checked)
                    {
                        this.lst.Credentials = new System.Net.NetworkCredential(txtlogin.Text.Trim(), txtPwd.Text.Trim(), txtDomain.Text.Trim());
                    }
                    else
                        lst.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    string text1 = GetValuefromSelected(this.lstList.SelectedItem, "Title");
                    ndList = lst.GetList(text1);
                    XmlNode ndVersion = ndList.Attributes["Version"];
                    this.listName = ndList.Attributes["ID"].Value;
                    this.listVersion = ndList.Attributes["Version"].Value;
                    cbShowUsr.Checked = !(String.IsNullOrEmpty(ndList.Attributes["ShowUser"].Value) ? false : Convert.ToBoolean(ndList.Attributes["ShowUser"].Value));
                    string fields = FormatToAllXML(RunXPathQuery(ndList, "/sp:List/sp:Fields")[0]);

                    XmlReader reader2 = new XmlTextReader(new StringReader(fields));
                    this.DsFields = new DataSet();
                    DsFields.ReadXml(reader2);
                    DataTable dt = new DataTable();
                    DataColumn dcNew = new DataColumn("ShowInNewForm", System.Type.GetType("System.Boolean"));
                    dt.Columns.Add(dcNew);
                    dt = DsFields.Tables[0];
                    dgvFields.AutoGenerateColumns = false;
                    dt.AcceptChanges();
                    dgvFields.DataSource = dt;
                }
                else
                    MessageBox.Show("Enter URL");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace);
            }
        }
        public static string GetValuefromSelected(object selectItem, string rowcolumn)
        {
            return ((DataRowView)selectItem).Row[rowcolumn].ToString();
        }

        private void rdCustom_CheckedChanged(object sender, EventArgs e)
        {
            grpCustom.Enabled = rdCustom.Checked;
        }

        private void ShowHideFields_Load(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string target = e.Link.LinkData as string;
            System.Diagnostics.Process.Start(target);
        }

        private void cbDispHiddenFlds_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void rdDefault_CheckedChanged(object sender, EventArgs e)
        {

        }

    }
}